// @ts-nocheck
/* -------------------------------------------------------------------------- */
/* 格式化输出eslint                                                                */
/* -------------------------------------------------------------------------- */

const chalk = require('chalk');
const stripAnsi = require('strip-ansi');
const table = require('text-table');
const { execSync } = require('child_process');

const exec = (cmd) => execSync(cmd, { encoding: 'utf-8', stdio: 'pipe' });

const getBlame = (filePath, line) => {
  const result = exec(`git blame -L ${line},${line} --incremental ${filePath} | grep author`);
  if (result?.length) {
    const [user, email] = result.split(/\n/).map(line => line.split(' ')[1]);
    return [user, email].join('');
  }
  return ''
};

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
 * Given a word and a count, append an s if count is not one.
 * @param {string} word A word in its singular form.
 * @param {int} count A number controlling whether word should be pluralized.
 * @returns {string} The original word with an s on the end if count is not one.
 */
function pluralize(word, count) {
  return count === 1 ? word : `${word}s`;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = function formatter(results) {
  let output = '\n',
    errorCount = 0,
    warningCount = 0,
    fixableErrorCount = 0,
    fixableWarningCount = 0,
    summaryColor = 'yellow';

  results.forEach((result) => {
    const messages = result.messages;
    if (messages.length === 0) {
      return;
    }
    errorCount += result.errorCount;
    warningCount += result.warningCount;
    fixableErrorCount += result.fixableErrorCount;
    fixableWarningCount += result.fixableWarningCount;

    let getShortPath = (filepath) => filepath.replace(process.cwd() + '/', '');
    let shortFilePath = result.filePath.replace(process.cwd() + '/', '');


    output += `${chalk.green(shortFilePath)} \n`;

    output += `${table(
      messages.map((message) => {
        let messageType;
        const [mpath, ruleName] = message.message.split(',');
        if (message.fatal || message.severity === 2) {
          messageType = chalk.red('error');
          summaryColor = 'red';
        } else {
          messageType = chalk.yellow('warning');
        }
        return [
          chalk.gray(`${shortFilePath}:${message.line}:${message.column}`),
          messageType,
          chalk.cyan(getShortPath(mpath)),
          chalk.dim(getBlame(shortFilePath, message.line)),
        ];
      }),
      {
        align: ['', 'r', 'l'],
        stringLength(str) {
          return stripAnsi(str).length;
        },
      }
    )
      .split('\n')
      .map((el) => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`)))
      .join('\n')
      }\n\n`;
  });

  const total = errorCount + warningCount;
  if (total > 0) {
    output += chalk[summaryColor].bold(
      [
        '\u2716 ',
        total,
        pluralize(' problem', total),
        ' (',
        errorCount,
        pluralize(' error', errorCount),
        ', ',
        warningCount,
        pluralize(' warning', warningCount),
        ')\n',
      ].join('')
    );
    if (fixableErrorCount > 0 || fixableWarningCount > 0) {
      output += chalk[summaryColor].bold(
        [
          '  ',
          fixableErrorCount,
          pluralize(' error', fixableErrorCount),
          ' and ',
          fixableWarningCount,
          pluralize(' warning', fixableWarningCount),
          ' potentially fixable with the `--fix` option.\n',
        ].join('')
      );
    }
  }
  // Resets output color, for prevent change on top level
  return total > 0 ? chalk.reset(output) : '';
};
